package pro.cherish.knowledgenotifywebsocket.web;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import pro.cherish.knowledgenotifywebsocket.cmmon.TransResult;
import pro.cherish.knowledgenotifywebsocket.socket.ScocketHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-09-13 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：TestSocketController
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-09-13 cherish
 */
@Controller
@RequestMapping("/smart/etl")
public class TestSocketController {

    //页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/socket");
        HttpSession session = request.getSession();
        session.setAttribute("userId",1L);
        mav.addObject("cid", cid);
        return mav;
    }

    //推送数据接口
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public Object pushToWeb(@PathVariable Long cid, String message, HttpServletRequest request) {
        try {
            TransResult transResult = new TransResult();
            transResult.setMessage("您好呀");
            //启动线程实现消息发送
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("开始大文件导入");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("导入结束");
                    // 发送通知
                    try {
                        ScocketHandler.sendtoUser(transResult, 1L);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cid;
    }
    @ResponseBody
    @RequestMapping("/socket/sendAll/{cid}")
    public Object sendAll(@PathVariable Long cid, String message, HttpServletRequest request) {
        try {
            ScocketHandler.sendAll("您好呀");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cid;
    }

}
